//
//  HEPatientsCircleViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2021/2/25.
//  Copyright © 2021 honglutec. All rights reserved.
//

#import "HEPatientsCircleViewController.h"
#import "UICollectionView+LTCollectionViewLayoutCell.h"
#import "HECircleTeamCell.h"
#import "HECircleChatManager.h"
#import "HEIMCircleChatController.h"
#import "HEApplyCirlceSquareViewController.h"
#import "HEManageSpecView.h"

static NSString * const reuseIdentitier = @"HECircleTeamCell";

typedef NSMutableArray <NSMutableArray<NSNumber *> *> IndexCountBySection;

@interface HEPatientsCircleViewController ()<UICollectionViewDataSource,UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, UIActionSheetDelegate, LTCollectionViewDynamicHeightCellLayoutDelegate, HECircleChatManagerDelegate>


@property (nonatomic, copy) NSArray *photoEntityFromWallJSONData;
@property (nonatomic, strong) NSMutableArray  <HEChatRoomModel *> *dataSource;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) IndexCountBySection *indexCountBySectionForHeight;
@property (strong, nonatomic) LTCollectionViewDynamicHeightCellLayout *customizeLayout;

@property (nonatomic) NSInteger cellColumn;
@property (nonatomic) CGFloat cellMargin;


@end

@implementation HEPatientsCircleViewController

static NSString *const JPSuspensionCacheMsgKey = @"JPSuspensionCacheMsgKey";
static NSString *const JPSuspensionDefaultXKey = @"JPSuspensionDefaultXKey";
static NSString *const JPSuspensionDefaultYKey = @"JPSuspensionDefaultYKey";

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    JPSEInstance.navCtr = self.navigationController;
    JPSEInstance.willSpreadSuspensionViewControllerBlock = ^(UIViewController<JPSuspensionEntranceProtocol> *targetVC) {
        [(HEIMCircleChatController *)targetVC setIsHideNavBar: YES];
    };
}

- (void)setupJPSEInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        // 是否可以播放提示音
        JPSEInstance.canPlaySound = YES;
        
//        // 配置展开时的提示音
//        JPSEInstance.playSpreadSoundBlock = ^{
//
//        };
//
//        // 配置闭合时的提示音
//        JPSEInstance.playShrinkSoundBlock = ^{
//
//        };
        
        JPSEInstance.cacheMsgBlock = ^(NSString *cacheMsg) {
            [[NSUserDefaults standardUserDefaults] setObject:cacheMsg forKey:JPSuspensionCacheMsgKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
        };
        
        JPSEInstance.cacheSuspensionFrameBlock = ^(CGRect suspensionFrame) {
            [[NSUserDefaults standardUserDefaults] setFloat:suspensionFrame.origin.x forKey:JPSuspensionDefaultXKey];
            [[NSUserDefaults standardUserDefaults] setFloat:suspensionFrame.origin.y forKey:JPSuspensionDefaultYKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
        };
        
    });
    
//    [self setupSuspensionView];
}

- (void)setupSuspensionView {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *cachaMsg = [[NSUserDefaults standardUserDefaults] stringForKey:JPSuspensionCacheMsgKey];
        if (cachaMsg) {
            HEPatientsCircleViewController *webVC = [[HEPatientsCircleViewController alloc] init];
            CGFloat x = [[NSUserDefaults standardUserDefaults] floatForKey:JPSuspensionDefaultXKey];
            CGFloat y = [[NSUserDefaults standardUserDefaults] floatForKey:JPSuspensionDefaultYKey];
            [JPSEInstance setupSuspensionViewWithTargetVC:webVC suspensionXY:CGPointMake(x, y)];
        }
    });
}

#pragma mark -

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
  
    self.title = @"圈子";
     
    [self initNav];
    [self initUI];
    [self buildData];
    [self setupJPSEInstance];
    
    [[HECircleChatManager sharedManager] addDelegate: self];
    [[HECircleChatManager sharedManager] initOpration];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:KChangeFontNotification object:nil];
}

- (void)refresh {
    [self.collectionView.lt_indexPathHeightCache invalidateAllHeightCache];
    [self collectionView:self.collectionView numberOfItemsInSection:0];
    [self.collectionView reloadData];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KChangeFontNotification object:nil];
    [[HECircleChatManager sharedManager] removeDelegate:self];
}

- (void)initNav {
    [self zx_setRightBtnWithText:@"申请" clickedBlock:^(ZXNavItemBtn * _Nonnull btn) {
        HEApplyCirlceSquareViewController *vc = [HEApplyCirlceSquareViewController new];
        [self.navigationController pushViewController:vc animated:YES];
    }];
    self.zx_navRightBtn.zx_tintColor = CNavBgColor;
}

- (void)initUI {
    self.view.backgroundColor = CViewBgColor;
    
    QMUIFillButton *specBtn = [[QMUIFillButton alloc] initWithFillColor:CNavBgColor titleTextColor:CNavBgFontColor];
    specBtn.titleLabel.font = DYBlodFont(17);
    [specBtn setTitle:@"管理规范" forState:UIControlStateNormal];
    [self.view addSubview: specBtn];
    [specBtn addTarget:self action:@selector(popSpecViewClick) forControlEvents:UIControlEventTouchUpInside];

    
    // 1.创建流水布局
    _customizeLayout = [[LTCollectionViewDynamicHeightCellLayout alloc] init];
    _customizeLayout.dynamicLayoutDelegate = self;

//    _customizeLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
//    _layout.estimatedItemSize = CGSizeMake(120, 100);

    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:_customizeLayout];
    _collectionView.backgroundColor = CViewBgColor;
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.showsHorizontalScrollIndicator = NO;
    _collectionView.alwaysBounceVertical = YES;
    _collectionView.bounces = YES;
    [self.view addSubview:_collectionView];
    
    [specBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(ZXNavBarHeight + 20);
        make.left.equalTo(self.view).offset(30);
        make.right.equalTo(self.view).offset(-30);
        make.height.offset(40);
    }];
    
    [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(specBtn.mas_bottom).offset(20);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    
    /// 设置此属性为yes 不满一屏幕 也能滚动
//    self.collectionView.alwaysBounceHorizontal = YES;
//    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.collectionView registerClass:[HECircleTeamCell class] forCellWithReuseIdentifier:@"HECircleTeamCell"];
}

- (void) buildData {
    
    _indexCountBySectionForHeight = [NSMutableArray array];
    _cellColumn = 2;
    _cellMargin = 0;
    
    NSMutableArray *entities = @[].mutableCopy;
    self.photoEntityFromWallJSONData = entities;
    
//    HEChatRoomModel *model = [HEChatRoomModel new];
//    model.roomName = @"dsds";
//    model.roomNum = 5;
//    model.users = @[@"https://www.honglutec.com:9998/group1/M00/00/14/rBDIOGA06eCAR4vOAACYseqvBWQ710.jpg",
//                    @"https://www.honglutec.com:9998/group1/M00/00/14/rBDIOGA06eCAR4vOAACYseqvBWQ710.jpg",
//                    @"https://www.honglutec.com:9998/group1/M00/00/14/rBDIOGA06eCAR4vOAACYseqvBWQ710.jpg",
//                    @"https://www.honglutec.com:9998/group1/M00/00/14/rBDIOGA06eCAR4vOAACYseqvBWQ710.jpg",
//                    @"https://www.honglutec.com:9998/group1/M00/00/14/rBDIOGA06eCAR4vOAACYseqvBWQ710.jpg",];
//    
//    self.dataSource = @[model];
}

#pragma mark -
- (void)popSpecViewClick {
    HEManageSpecView *manageView = [HEManageSpecView new];
    manageView.vc = self;
    [manageView show];
}

#pragma mark - LTCollectionViewDynamicHeightCellLayoutDelegate
- (NSInteger) numberOfColumnWithCollectionView:(UICollectionView *)collectionView
                          collectionViewLayout:( LTCollectionViewDynamicHeightCellLayout *)collectionViewLayout{
    return _cellColumn;
}

- (CGFloat) marginOfCellWithCollectionView:(UICollectionView *)collectionView
                     collectionViewLayout:(LTCollectionViewDynamicHeightCellLayout *)collectionViewLayout{
    return _cellMargin;
}


- (NSMutableArray<NSMutableArray *> *)indexHeightOfCellWithCollectionView:(UICollectionView *)collectionView collectionViewLayout:(LTCollectionViewDynamicHeightCellLayout *)collectionViewLayout {
    return _indexCountBySectionForHeight;
}


#pragma mark UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSMutableArray<NSNumber *> *indexHeightArray = @[].mutableCopy;
    for (NSInteger i = 0; i < self.dataSource.count; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:section];
        CGFloat height= [collectionView lt_heightForCellWithIdentifier:reuseIdentitier fixedWidth:KScreenWidth cacheByIndexPath:indexPath configuration:^(HECircleTeamCell *cell) {
            cell.lt_enforceFrameLayout = NO;
            cell.model = self.dataSource[indexPath.row];
        }];
        
        [indexHeightArray addObject:@(height)];
    }
    _indexCountBySectionForHeight[section] = indexHeightArray;
    return self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    HECircleTeamCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentitier forIndexPath:indexPath];
    cell.lt_enforceFrameLayout = NO;
    cell.model = self.dataSource[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    HEChatRoomModel *model = self.dataSource[indexPath.row];
    
//    JPSEInstance.suspensionView.hidden = YES;

    [[HECircleChatManager sharedManager] switchRoomVC:model isFromChatPage:NO callback:^(HEIMCircleChatController * _Nonnull vc) {
            
        }];
}

#pragma mark - HECircleChatManagerDelegate
- (void)allTeams:(NSArray <HEChatRoomModel *> *)teams {
    _dataSource = [NSMutableArray arrayWithArray:teams];
    [self refresh];
}

- (void)updateTeamInfo:(HEChatRoomModel *)team index:(NSInteger)index {
//    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
//    HECircleTeamCell *cell =  [self.collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentitier forIndexPath:indexPath];
 
    [self.collectionView reloadData];
}

@end
